package ua.com.musicdownloader.model;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * User: Ostap
 * Date: 20.05.12
 * Time: 17:54
 * To change this template use File | Settings | File Templates.
 */
public class DAO {
    private Connection connection;

    public boolean checkLogin(String username, String password) {
//        try {
//			Class.forName("com.mysql.jdbc.Driver");
//		} catch (ClassNotFoundException e) {
//
//		}
        if (username == null || username.equals("") || password == null || password.equals("")) {
            return false;
        }
        Statement st = null;
        connection = null;
        InitialContext initialContext=null;
        DataSource ds = null;
        try {
            try {
                initialContext = new InitialContext();
                ds = (DataSource) initialContext.lookup("java:comp/env/jdbc/upmusic");
            } catch (NamingException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            connection = ds.getConnection();//DriverManager.getConnection("jdbc:mysql://localhost:3306/uploadmusicdb", "developer", "ostap");
            st = connection.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM Users WHERE Username ='" + username + "'");
            if(rs.next()){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }   finally {
            if(st!=null){
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        return false;

    }
}
